package com.atguigu.pratice2;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*synchronized 和 lock 的区别
1.synchronized是关键字，而lock是工具类
2.synchronized 是独占锁+非公平锁  ReentrantLock是独占锁+非公平锁(默认)+公平锁同时具备
3.synchronized 是必须要等前一个进程使用完资源，后边的进程才能使用该资源
lock 具有，超时等待，中途退出取消机制，
4.两者都是可重入锁
 */
public class SyncVSLock {
    public synchronized void m1(){
        //线程睡眠几秒
        System.out.println(Thread.currentThread().getName()+"------come in...");
        try {TimeUnit.SECONDS.sleep(4);} catch (InterruptedException e) {throw new RuntimeException(e);}

    }
    Lock lock = new ReentrantLock();//中途退出取消机制
    public  void m2() throws InterruptedException {

        if (lock.tryLock(6L,TimeUnit.SECONDS)) {  //尝试调用锁
            try {
                //线程睡眠几秒
                System.out.println(Thread.currentThread().getName()+"------come in...");
                try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {throw new RuntimeException(e);}
                 } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName()+"-----leave out");
            }
        }
    public static void main(String[] args) {
        SyncVSLock syncVSLock = new SyncVSLock();

        new Thread(() -> {
            try {
                syncVSLock.m2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1").start();
        //线程睡眠几秒
        try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}

        new Thread(() -> {
            try {
                syncVSLock.m2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t2").start();

    }
}
